const fsp = require("fs/promises");
const readline = require('readline'); // 用于读取命令行输入

/**
 * 封装 fsp.access 判断路径是否存在
 */
async function accessPath (p) {
  try {
    await fsp.access(p);
    return true;
  } catch {
    return false;
  }
}

// 时间戳自动转换
function fmtDate (timestamp = Date.now()) {
  const format = t => String(t).padStart(2, '0');
  if (String(timestamp).length < String(Date.now()).length) timestamp *= 1000; // auto unit: s or ms.
  const date = new Date(timestamp);
  // if (isNaN(date.getTime())) throw new Error('Invalid timestamp');
  const [Yea, Mon, Day, Hou, Min, Sec] = [
    date.getFullYear(),
    format(date.getMonth() + 1),
    format(date.getDate()),
    format(date.getHours()),
    format(date.getMinutes()),
    format(date.getSeconds()),
  ];
  // 完整的处理时间字符串
  const getFull = (option = "YYYY-MM-DD hh:mm:ss") =>
    option
      .replace("YYYY", Yea)
      .replace("YY", String(Yea).slice(2))
      .replace("MM", Mon)
      .replace("DD", Day)
      .replace("hh", Hou)
      .replace("mm", Min)
      .replace("ss", Sec);
  return {
    getFull,
    getDate6D: getFull('YYMMDD'),
    getTime6D: getFull('hhmmss'),
    getNow12: getFull('YYMMDDhhmmss'),
  }
}

// 动态更新的进度行
function updateProgress (text, singleLine = true) {
  const maxLength = process.stdout.columns || 100; // 自动适配终端宽度
  const end = singleLine ? '' : '\n'
  process.stdout.write('\r' + text + ' '.repeat(Math.max(0, maxLength - text.length - 2)) + end);
}

function waitForAnyKey (cbfn, text = '\n按任意键退出...') {
  return new Promise((resolve) => {
    const rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });

    console.log(text);

    // Windows 下需要这样处理
    if (process.platform === 'win32') {
      require('readline').emitKeypressEvents(process.stdin);
      process.stdin.setRawMode(true);
    }

    process.stdin.once('keypress', () => {
      if (process.platform === 'win32') {
        process.stdin.setRawMode(false);
      }
      rl.close();
      if (typeof cbfn == "function") cbfn();
      resolve();
    });
  });
}

async function anyKeyExit (code = 0, force = true) {
  if (force || process.pkg) await waitForAnyKey(null);
  process.exit(code);
}

async function returnError (msg, beforeExit) {
  console.error(`\x1b[33m${msg}\x1b[0m`);
  if (typeof beforeExit == 'function') await beforeExit();
  console.error('\x1b[31m程序已终止。\x1b[0m');
  await anyKeyExit(1); // 终止程序
}

function confirmAction (promptText = '是否继续', Y = 'y', N = 'n') {
  promptText += `(${Y}/${N})? `
  return new Promise((resolve) => {
    const rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });

    rl.question(promptText, (answer) => {
      rl.close();
      const normalized = answer.trim().toLowerCase();
      if (normalized === Y) {
        resolve(true);
      } else if (normalized === N) {
        resolve(false);
      } else {
        console.log(`请输入 ${Y} 或 ${N}`);
        resolve(confirmAction(promptText)); // 输入非法时递归重试
      }
    });
  });
}

module.exports = {
  accessPath, fmtDate, updateProgress,
  waitForAnyKey, anyKeyExit, returnError, confirmAction
}
